import os
import sys
from simple_chalk import chalk


# for chalk works
os.system("")
def addParentPath():
    parentPath = os.path.abspath(os.path.join(__file__, "../.."))
    sys.path.append(parentPath)


addParentPath()

from config import config

# print(config, "<=========")


def getWordBookFilePath(book):
    return os.path.abspath(os.path.join(__file__, "../../wordBooks/%s.txt" % book))


def getNewWordsTempFilePath():
    return os.path.abspath(os.path.join(__file__, "../temp.txt"))


def checkContent(con):
    if not con:
        print(chalk.red("not found content, please input new words"))
        return False

    lines = [
        line.strip()
        for line in con.split("\n")
        if line.strip() and not line.strip().startswith(config.get("commentLineMark"))
    ]

    dailyCount = config.get("dailyCount")
    lineCount = len(lines)
    daysNum = lineCount // dailyCount
    remainNum = lineCount % dailyCount
    print()
    print(chalk.yellow("Info: You have inputed words for %d days" % daysNum))
    print()
    if remainNum > 0:
        print(
            chalk.bold.red(
                "Error: there are %d extra words, \nplease input more(to %d) or delete them"
                % (remainNum, dailyCount)
            )
        )
        return False
    else:
        return True


def appendNewWords(book = "PET"):
    tempFile = getNewWordsTempFilePath()
    # print('tempFile====>', tempFile)
    bookFile = getWordBookFilePath(book)
    con = ""
    with open(tempFile, "r", encoding="utf8") as f:
        con = f.read()

    if checkContent(con):
        with open(bookFile, "a", encoding="utf8") as f:
            f.write(config.get("newContentLineMark") + "\n\n" + con + "\n\n")
            print("write to %s done!" % os.path.split(bookFile)[-1])

        with open(tempFile, "w", encoding="utf8") as f:
            f.write("")
            print("has cleared content in %s file" % os.path.split(tempFile)[-1])
        
        if __name__ == '__main__':
            sys.exit(0)
        else:
            return True
    else:
        if __name__ == '__main__':
            sys.exit(1)
        else:
            return False


if __name__ == "__main__":
    # pet = getWordBookFilePath("PET")
    # print(pet)
    # tmp = getNewWordsTempFilePath()
    # print(tmp)
    appendNewWords()
    # os.system("wtest -h")
